<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Конфигурационный файл
 *
 */
class Setting_model extends CI_Model{

    private $default_settings = Array(
        'chart'         => array ('width'=>800,'height'=>400,'reload'=>600,'widthpreview'=>400,'heightpreview'=>200, 'usepreview' => 'checked'),   //checked //ширина графиков //высота графиков //обновление графиков в сек
        'chart_period'  => array ('0'),                                      //период в днях
        'chart_mode'    => array ('0'),                         //опции отображения графиков
//        'custom_css'    => 'body { background-color: #f9f9f9; }'
        'body_color'    => '#f9f9f9'
    );

    private $x_grid = Array( //все возможные форматы оси времени
                         1 => 'HOUR:1:DAY:1:HOUR:2:0:"%H:%M"',                  //1 сутки
                         2 => 'HOUR:2:DAY:1:HOUR:4:0:"%H:%M"',                  //2 суток
                         3 => 'HOUR:4:DAY:1:HOUR:8:0:"%H:%M"',                  //3 суток
                         4 => 'HOUR:6:DAY:1:DAY:1:86400:"%d,%A"',               //1 неделя
                         5 => 'HOUR:12:DAY:1:DAY:1:86400:"%d"',                 //2 недели
                         6 => 'HOUR:24:DAY:1:DAY:1:86400:"%d"'                  //1 месяц
                        );
    
    private $x_grid_prev = Array( //все возможные форматы оси времени
                         1 => 'HOUR:1:DAY:1:HOUR:4:0:"%H:%M"',                  //1 сутки
                         2 => 'HOUR:2:DAY:1:HOUR:8:0:"%H:%M"',                  //2 суток
                         3 => 'HOUR:4:DAY:1:HOUR:12:0:"%H:%M"',                  //3 суток
                         4 => 'HOUR:6:DAY:1:DAY:1:86400:"%d"',               //1 неделя
                         5 => 'HOUR:12:DAY:1:DAY:1:86400:"%d"',                 //2 недели
                         6 => 'HOUR:24:DAY:1:DAY:2:86400:"%d"'                  //1 месяц
                        );

    public function __construct() {
        parent::__construct();
        $this->load->helper('cookie');
        $this->init_settings();
    }

    private function init_settings(){
        if(filter_input(INPUT_COOKIE, 'default_settings') !== NULL){
            $this->get_default_settings();
        }else{
            $this->set_default_settings();
        }
    }

    /**
     *
     * Cookie
     */

    private function set_default_settings(){
        set_cookie('default_settings', serialize($this->default_settings), $this->config->item('cookie_life_time'));
    }

    public function validate_cookie(){
        $ar1 = $this->default_settings;
        $ar2 = unserialize(get_cookie('default_settings'));
        
        if (!is_array($ar2['chart'])){ 
            $ar2['chart'] = array();
        }
        $result = array_diff_key($ar1['chart'],  $ar2['chart']);

        if(count($result) > 0){
            //echo "\n=============delete_cookie============================\n";
            log_message("INFO", "delete_cookie \n".print_r($ar2,true));
            delete_cookie('default_settings');
            $this->init_settings();
            redirect('');
        }
    }

    private function get_default_settings(){
        $raw_settings = unserialize(get_cookie('default_settings'));
        $this->default_settings = $this->check_data_settings($raw_settings);
    }

    public function update_settings($chart, $chart_period, $chart_mode, $body_color){
        $settings = $this->check_data_settings(array('chart'=>$chart,'chart_period'=>$chart_period,'chart_mode'=>$chart_mode,'body_color'=>$body_color));
        set_cookie('default_settings', serialize($settings), $this->config->item('cookie_life_time'));
        return json_encode($settings);
    }

    /**
     * @param array $in_settings
     * @return array
     */
    private function check_data_settings($in_settings){

        $this->validate_cookie();

        $chart        = isset($in_settings['chart'])        && count($in_settings['chart'])         != 0 ?$in_settings['chart']:NULL;
        $chart_period = isset($in_settings['chart_period']) && count($in_settings['chart_period'])  != 0 ?$in_settings['chart_period']:NULL;
        $chart_mode   = isset($in_settings['chart_mode'])                                                ?$in_settings['chart_mode']:NULL;

        $chart_c        = array();
        $chart_period_c = array();
        $chart_mode_c   = array();
        
        $body_color_c = isset($in_settings['body_color']) && strlen($in_settings['body_color']) > 0?$in_settings['body_color']:$this->default_settings['body_color'];
        
        if($chart == NULL) $chart_c = $this->default_settings['chart'];
        else{
            $chart_c['width'] = my_check_digit($chart['width'])?$chart['width']:$this->default_settings['chart']['width'];
            $chart_c['height'] = my_check_digit($chart['height'])?$chart['height']:$this->default_settings['chart']['height'];

            $chart_c['widthpreview']  = isset ($chart['widthpreview']) && my_check_digit($chart['widthpreview']) && preg_match("/\d{0,3}/",$chart['widthpreview'])?$chart['widthpreview']:$this->default_settings['chart']['widthpreview'];
            $chart_c['heightpreview'] = isset ($chart['heightpreview']) && my_check_digit($chart['heightpreview']) && preg_match("/\d{0,3}/",$chart['heightpreview'])?$chart['heightpreview']:$this->default_settings['chart']['heightpreview'];

            $chart_c['usepreview'] = isset($chart['usepreview'])?$chart['usepreview']:$this->default_settings['chart']['usepreview'];
            $chart_c['reload'] = (array_key_exists($chart['reload'], $this->config->item('chart_reload')))?my_digit_only($chart['reload']):$this->default_settings['chart']['reload'];
        }
        
        if($chart_period == NULL){
            $chart_period_c[] = '0';
        }else{
            foreach ($chart_period as $value) {
                $str_value = (string)$value;
                if(array_key_exists($str_value, $this->config->item('form_period'))) $chart_period_c[] = $str_value;
            }
            if(0 == count($chart_period_c)) $chart_period_c[] = $this->default_settings['chart_period'];
        }

        if($chart_mode != NULL){
            foreach ($chart_mode as $value) { //TODO разные входные данные
                $int_value = my_digit_only($value);
                if(array_key_exists($int_value, $this->config->item('chart_mode'))) $chart_mode_c[] = $int_value;
            }
        }

        $out_settings = array('chart' => $chart_c,'chart_period' => $chart_period_c,'chart_mode' => $chart_mode_c, 'body_color' => $body_color_c);
        return $out_settings;
    }

    /**
     * @return array
     */
    public function get_settings(){
        return $this->default_settings;
    }
    
    /**
     * Charts
     *
     */
    public function get_chart_width(){
        return $this->default_settings['chart']['width'];
    }
    public function get_chart_height(){
        return $this->default_settings['chart']['height'];
    }
    public function get_chart_width_preview(){
        return $this->default_settings['chart']['widthpreview'];
    }
    public function get_chart_height_preview(){
        return $this->default_settings['chart']['heightpreview'];
    }
    public function get_chart_use_preview(){
        return ($this->default_settings['chart']['usepreview'] == 'checked');
    }
    public function get_chart_periods(){
        return $this->default_settings['chart_period'];
    }
    public function get_chart_reload(){
        return $this->default_settings['chart']['reload'];
    }
    public function get_chart_mode(){
        $res = '';
        foreach ($this->default_settings['chart_mode'] as $value) {
            $chart_mode = $this->config->item('chart_mode');
            $res .= ' '.$chart_mode[$value][0];
        }
        return $res;
    }
    /*public function get_max_width_for_lightbox(){
        return $this->max_width_for_lightbox;
    }*/
    public function get_chart_xgrid_param($period,$is_prev=FALSE){
        if($is_prev)
            $x_grid = &$this->x_grid_prev;
        else 
            $x_grid = &$this->x_grid;
        
        if($period < 3){
            if($period < 1) $period = 1;
            $res = $x_grid[$period];
        }elseif($period <= 7){
//            $res = $this->x_grid[4];
            $res = $x_grid[4];
        }elseif($period <= 14){
            $res = $x_grid[5];
        }elseif($period <= 25){
            $res = $x_grid[6];
        }else{
            $res = $x_grid[6];
        }
        return $res;
    }
    
    public function get_body_color(){
        return $this->default_settings['body_color'];
    }

    public function write_to_log($data_in){
        $filelog = $this->config->item('user_access_log');
	$res = false;
        $data = sprintf("%s: %s\t%s\t\t%s\n",date("Y.m.d H:i:s"),$_SERVER['REMOTE_ADDR'],$this->session->userdata['login'],$data_in);
	if(!file_exists($filelog)){
		$bt = file_put_contents($filelog,$data);
                $res = ($bt > 0 )?TRUE:'File not found';
	}elseif(!is_writable($filelog)){
		$res = 'File not writable';
	}else{
		$bt = file_put_contents($filelog,$data,FILE_APPEND);
                $res = ($bt > 0 )?TRUE:'File not saved';
	}
	return $res;
    }
}
